<template>
  <view class="page index-page video-center-page rec-bag-pop-page" :class="visibleJobTask? 'lingdang-job' : ''">
    <uni-navbar
      :border="false"
      :fixed="true"
      :height="barHeight"
      :rightWidth="120"
      :leftWidth="120"
      :leftIcon="!isMpWeixinH5"
      titleStyle="color:#fff;fontSize:18px;"
      :bgColor="isWhiteAppBar ? '#FF5500' : 'transparent'"
      :placeholder="false"
      :autoBack="false"
      :backNative="true"
    >
      <template #left>
        <view class="flex items-center">
          <image v-if="(isH5 && !isMpWeixinH5) || isMpWeixin" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;" @click="returnBackEv"></image>
          <text style="font-size:36rpx;font-weight:bold;color:#fff;padding-left:32rpx;">
            {{curVideoInfo.findex ? `第${curVideoInfo.findex}集` :''}}
          </text>
        </view>
      </template>
      
    </uni-navbar>

    <view
      class="box-1"
      :style="{paddingTop: 0}"
    >
      <view v-if="isLogin" class="inner-cont">
        <swiper class="swiper" 
          :circular="false" 
          :vertical="true"
          :current="currentIdx"
          :indicator-dots="false" 
          :autoplay="false" 
          :interval="5000"
          :duration="500"
          @change="swiperChange"
        >
          <block v-for="(item, index) in videoList" :key="item.randomId">
            <swiper-item class="swiper-item" :iddx="index" :xid="item.randomId"  @click="clickVideo">
              <block v-if="!isH5 && item.filmId">
                <view class="swiper-item-dom" v-if="visibleSwiperItem(index)">
                  <video 
                    :ref="item.randomId"
                    :id="item.randomId"
                    :src="item.url" 
                    :poster="item.poster"
                    :autoplay="item.autoplay"
                    :playsinline="true"
                    :webkit-playsinline="true"
                    x5-video-player-type="h5"
                    poster-size="fill"
                    object-fit="cover"
                    object-position="top"
                    class="item-video"
                    :controls="isMpWeixin?true:false"
                    :show-play-btn="true"

                    play-btn-position="center"
                    :page-gesture="false"
                    :show-progress="false"

                    :show-mute-btn="false"
                    :show-fullscreen-btn="false"
                    @play="onPlay"
                    @pause="onPause"
                    @ended="onEnded"
                    @progress="progressEv"
                    @timeupdate="timeupdateEv"
                  ></video>

                  <view class="process-bar" @click.stop="clickProcess($event, item)">
                    <view class="bar-bg">
                      <view class="process-ing" :style="{ width: item.percent + '%' }"></view>
                    </view>
                  </view>
                </view>
              </block>
              <block v-else-if="item.filmId">
                <view class="swiper-item-dom" :id="item.randomId" :ref="item.randomId"></view>
              </block>
            </swiper-item>
          </block>
        </swiper>
      </view>
    </view>

    
    <view class="tixiantip-block" v-if="countTxTxt">
      <view>{{ countTxTxt }}</view>
      <view class="inn-box">
        <view>提现</view>
        <view>0.3元</view>
      </view>
    </view>

    <view v-if="lingdangTxt" :class="['job-clock-block', countTxTxt? 'geng-block': '']" @click="clickLingdang">
      <image :src="staticHost+'/video_clock_ld.png'" class="lingdang" :class="[firstLingdangShow? 'init-show' : '']"></image>
      <view class="down-num">
        <text class="e-txt" >{{lingdangTxt}}</text>
      </view>
    </view>

    <view class="beisu" @click.stop="showBeisu">
      <image :src="staticHost + '/video_speed.png'" style="width:56rpx;diaplay:block;margin-bottom:0;" mode="widthFix"></image>
      <view>倍速</view>
    </view>

    <view class="right-bottom">
      <view class="change-mv" @click="switchOtherFilm" style="margin-right:32rpx;" >
        <image :src="staticHost + '/video_change_mv.png'" style="width:56rpx;" mode="widthFix"></image>
        <view>换一部</view>
      </view>

      <view class="watch-log" @click="toWatchHistory">
        <image :src="staticHost + '/watch-log.png'" style="width:56rpx;" mode="widthFix"></image>
        <view>观看记录</view>
      </view>
      
      <!-- <view class="zan-kls" style="margin-left:32rpx;" >
        <image :src="staticHost + '/video_zan.png'" style="width:56rpx;" mode="widthFix" @click.stop="loveEv"></image>
        <view>1233</view>
      </view> -->
    </view>


    <view class="film-info" v-if="curVideoInfo && curVideoInfo.filmId">
      <image class="cover-img" :src="curVideoInfo.coverImg"></image>
      <view>
        <view class="font18" style="line-height: 20px;">{{curVideoInfo.name}}</view>
        <view class="font12" style="margin-top:10rpx;">
          {{curVideoInfo.typeName}}.全 {{curVideoInfo.fcount}}集</view>
      </view>
    </view>

    <u-popup
      v-model="visibleVideoSpeed"
      mode="bottom"
      :mask-close-able="true"
      width="100%"
      border-radius="48"
      height="auto"
      z-index="10080"
      @close="visibleVideoSpeed=false"
    >
      <view class="speed-hd">
        倍速
      </view>
      <view class="speed-content">
        <view v-for="item in speedConf" :key="item.id" 
          :class="['speed-option', curVideoInfo.speed == item.value? 'active' : '']"
          @click="changePlaySpeed(item)"
        >
          {{item.label}}
        </view>
      </view>
    </u-popup>

    <!-- 第一天送6.68领取金币 -->
    <u-popup
      v-model="isVisFirstPop"
      class="rec-bag-pop"
      :border-radius="12"
      mode="center"
      :mask="true"
      z-index="10081"
      :mask-close-able="false"
      style="backround:transparent;"
    >
      <view :class="['relative', isMpKuaishou ? 'ks-rec-dia' : '']" style="padding-top:100rpx;">
        <image :src="staticHost + '/video_pop_bg.png'" mode="widthFix" style="width:600rpx;"></image>
        <image :src="staticHost + '/video_rec_top.png'" mode="widthFix" class="absolute" 
          style="top:0;width:338rpx;z-index:10;left: 0;right: 0;margin: 0 auto;"
        ></image>

        <view class="absolute" style="top:280rpx;width:100%;color:#FF282D; text-align:center;">
          <view class="font-medium" style="font-size:40rpx;">恭喜获得新人现金奖励</view>
          <view class="flex items-baseline justify-center font-b" style="margin:48rpx 0 20rpx;" >
            <text style="font-size: 120rpx;line-height: 120rpx;font-weight:bold;margin-right:16rpx">{{accountInfo.initAmount}}</text>
            <text style="font-size: 44rpx;">元</text>
          </view>
          <view class="font14">可直接提现</view>
        </view>

        <button class="pop-rec-btn linear" style="bottom: 56rpx;" @tap="firstReceiveEv">立即收下</button>
      </view>
    </u-popup>


    <!-- 签到领金币 -->
    <u-popup
      v-model="isVisibleSignPop"
      class="rec-bag-pop"
      :border-radius="12"
      mode="center"
      :mask-custom-style="{background: 'rgba(0, 0, 0, 0.6)'}"
      :mask-close-able="false"
      z-index="10081"
    >
      <view :class="['relative', isMpKuaishou ? 'ks-rec-dia' : '']" style="padding-bottom:100rpx;">
        <image :src="staticHost + '/video_pop_bg.png'" mode="widthFix" style="width:600rpx;"></image>
        
        <view class="absolute" style="top:0;width:100%;padding:56rpx 48rpx 0;">

          <view class="flex justify-between" style="color:#FF282D;">
            <view class="flex flex-col">
              <view class="font16 font-medium">每日签到</view>
              <view class="font-bold" style="font-size:60rpx;">领现金</view>
              <view class="font12">每天来签到 天天领现金</view>
            </view>
            <image :src="staticHost + '/video_red_bag.png'" mode="widthFix" style="width:138rpx;"></image>
          </view>
          
          <view class="flex items-baseline justify-center relative" style="margin:24rpx 0 0; color:#FF282D;" >
            <text class="font-b" style="font-size: 120rpx;margin-right:16rpx">2</text>
            <text class="font-b" style="font-size: 50rpx;">元</text>
            <view class="zuigao">
              最高
            </view>
          </view>
          <view class="font14" style="text-align:center;color:#FF282D;">直接到账</view>
        </view>

        <button class="pop-rec-btn linear" @click="signReceiveEv">立即领</button>
        <image class="close-ico" :src="staticHost + '/video_pop_close.png'" mode="widthFix" @click="signPopHideEv"></image>
      </view>
    </u-popup>

    <!-- 签到领金币成功 -->
    <u-popup
      v-model="isVisibleSignSuccess"
      class="rec-bag-pop"
      :border-radius="12"
      mode="center"
      :mask-custom-style="{background: 'rgba(0, 0, 0, 0.6)'}"
      :mask-close-able="true"
      z-index="10081"
      @close="receiveDailySuccessPopHideEv"
    >
      <view :class="['relative', isMpKuaishou ? 'ks-rec-dia' : '']" style="padding-bottom:100rpx;">
        <image :src="staticHost + '/video_pop_bg.png'" mode="widthFix" style="width:600rpx;"></image>
        
        <view class="absolute" style="top:0;width:100%;padding:56rpx 48rpx 0;">

          <view class="flex justify-center items-center" style="width:100%;">
            <image :src="staticHost + '/wf_zfb.png'" mode="widthFix" style="width:48rpx;margin-right:20rpx;"></image>
            <view class="font-bold" style="font-size:40rpx;">签到成功</view>
          </view>
          <view class="flex items-baseline justify-center relative" style="margin:60rpx 0 0; color:#FF282D;" >
            <text class="font-bold" style="font-size: 120rpx;line-height: 120rpx;margin-right:16rpx">
              {{ dailyReward }}
            </text>
            <text class="font-bold" style="font-size: 60rpx;margin-right:16rpx;margin-top:-10rpx;">
              元
            </text>
          </view>
          <view class="font14 tx-info"
            :style="{backgroundImage: `url(${staticHost + '/video_tixian.png'})`}"
          >
            <view class="font16 font-bold">已打款到支付宝</view>
            <view class="flex justify-between" style="margin:36rpx 0">
              <text class="cor-grey">收款账户：</text>
              <text>{{userPayaccount.accoutNo || ''}}</text>
            </view>
            <view class="flex justify-between">
              <text class="cor-grey">打款方式：</text>
              <text>支付宝</text>   
            </view>
          </view>
        </view>
        <image class="close-ico" :src="staticHost + '/video_pop_close.png'" mode="widthFix" @click="receiveDailySuccessPopHideEv"></image>
      </view>
    </u-popup>

    <OnlineCircle ref="onlineCircle" :account-info="accountInfo" 
      @hideTaskPop="hideTaskPop" 
      @showTaskPop="showTaskPop" 
      @getAccout="getAccout"
      @showAwardFinishTip="showAwardFinishTip"
    ></OnlineCircle>

    <WfCommonPop 
      v-if="visibleCmTip" 
      v-model="visibleCmTip" 
      :config="tipConfig" 
      @hideEv="hideCmTip"
    ></WfCommonPop>

    <Jobs 
      v-if="visibleJobTask" 
      v-model="visibleJobTask" 
      @hideJobTask="hideJobTask"
    ></Jobs>
  </view>
</template>

<script>
import OnlineCircle from './components/OnlineCircle'
import WfCommonPop from './components/WfCommonPop';
import Jobs from './components/Jobs';

import { isMpWeixin, isMpAlipay, isMpBaidu, isMpToutiao, isMpKuaishou, isH5 } from '@/utils/platform';
import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'
import { dateFormat, formatCountdown } from '@/utils/util'
import { EventBus } from '@/utils/event-bus'

// #ifdef H5
import DPlayer from 'dplayer';
// #endif
import { GetMoneyDetail, RecvDaily, GetCurFilms, GetNextFilms, GetAccout, ReceiveFirst } from '@/pages/welfare/api/index';
import { serviceMobile, staticHost } from '@/setting';

const app = getApp();
let onlineTxTimer;
let lingdangTxtTimer;
let isFirst = false;

export default {
  mixins: [ statusBarInfo ],
  components: {
    OnlineCircle,
    WfCommonPop,
    Jobs
  },
  computed: {
    curVideoInfo() {
      if (this.currentIdx >= 0) {
        return this.videoList[this.currentIdx] || {};
      }
      return {};
    },
    dailyReward() {
      let amount = this.accountInfo?.activityDaily?.amount;
      if (amount) {
        return (amount/100).toFixed(2)
      }
      return '0.00';
    }
  },
  data() {
    return {
      visibleJobTask: false,
      visibleCmTip: false,
      isVisFirstPop: false,
      isVisibleSignPop: false,
      isVisibleSignSuccess: false,
      isMpWeixin,
      isMpAlipay,
      isMpKuaishou,
      isH5,
      contactsMobile: serviceMobile,
      accountInfo: {},
      isWhiteAppBar: false,
      staticHost,
      isLogin: true,
      isMpWeixinH5: false,
      visibleVideoSpeed: false,
      firstLingdangShow: false,
      userPayaccount: {},
      tipConfig: {
        title: '温馨提示',
        content: '',
        isConfirm: false,
        btnTxt: '好的',
      },
      countTxTxt: '',
      lingdangTxt: '',
      speedConf: [
        { id: 'sp_1', value: 2, label: '2X' },
        { id: 'sp_2', value: 1.75, label: '1.75X' },
        { id: 'sp_3', value: 1.5, label: '1.5X' },
        { id: 'sp_4', value: 1.25, label: '1.25X' },
        { id: 'sp_5', value: 1, label: '1.0X(默认)' },
        { id: 'sp_6', value: 0.75, label: '0.75X' },
      ],
      videoList: [],
      poster: staticHost + '/peiyin/h_tu3.jpg',
      currentIdx: 0,
      cg: 0,
      menuBottom: isMpAlipay ? 16: 0,
    };
  },
  async onLoad() {
    let _self = this;
    isFirst = true;
    setTimeout(() => {
      isFirst = false;
    }, 1000)
    await this.getAccout();
    this.firstLingdangShow = true;
    setTimeout(() => {
      this.firstLingdangShow = false;
    }, 1200);

    if (!this.accountInfo.recieved) {
      this.isVisFirstPop = true;
    } else if (this.accountInfo?.activityDaily?.status == 0) {
      this.isVisibleSignPop = true;
      // 暂停转圈
      if (this.$refs.onlineCircle) {
        this.$refs.onlineCircle.pauseAniEv()
      }
    }

    if (typeof app.globalData.onlineBeginNumber == 'undefined') {
      app.globalData.onlineBeginNumber = 180;
    }

    if (typeof app.globalData.lingdangBeginNumber == 'undefined') {
      // 从本地缓存取
      app.globalData.lingdangBeginNumber = 600;
    }
    
    let userId = this.accountInfo.id || '';
    let today = dateFormat('YYYY-mm-dd', new Date()) +'_' + userId;

    if (this.accountInfo?.activityDaily?.ftimes >= 4) {
      let tixianThan3 = uni.getStorageSync('tixianThan3');
      if (tixianThan3) {
        if (today != tixianThan3) {
          // 需要倒计时
          this.startOnlineTxTimer(today)
        }
      } else {
        this.startOnlineTxTimer(today)
      }
    } else {
      this.countTxTxt = '';
      app.globalData.onlineBeginNumber = 180;
    }

    let lingdangStage = uni.getStorageSync('lingdangStage');
    if (lingdangStage) {
      if (today != lingdangStage) {
        this.startJobLingdangTimer(today)
      }
    } else {
      this.startJobLingdangTimer(today)
    }

    this.getCurFilms((data) => {
      // 添加占位容器
      this.addNextEmpty()
      if (isH5) {
        setTimeout(() => {
          if (!this.curVideoInfo.dplayer) {
            this.initVideo();
          }
        }, 200)
      }
    });

    if (!isH5) {
      let userInfo = app.globalData.userInfo;

      if (userInfo && userInfo.userId) {
        if (this.$uma && this.$uma.trackEvent) {
          this.$uma.trackEvent('enter_video_index', userInfo);
        }
      }
      
      if (!userInfo || !userInfo.userId) {
        setTimeout(() => {
          // 跳转登录
          this.$navigateTo('/pages/login/phone')
        }, 1000)
      }
    }
    
    function ready() {
      console.log('ready 是否是小程序::', window.__wxjs_environment === 'miniprogram');
      if (window.__wxjs_environment === 'miniprogram') {
        // 是小程序环境
        _self.isMpWeixinH5 = true;
      }
    }
    if (isH5) {
      setTimeout(() => {
        if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
          document.addEventListener('WeixinJSBridgeReady', ready, false)
        } else {
          ready()
        }
      }, 500)

      await this.$onLaunched;
      let { appId, channel, version, deviceId } = app.globalData
      let { userId, userNo, loginId, displayName } = app.globalData.userInfo || {};
      // console.log('end 借宿了', app.globalData.userInfo);
      console.log('结束了>>>>>>>>', loginId, channel, userId, userNo, displayName, appId, version, deviceId);
      setTimeout(() => {
        // H5友盟
        const {aplus_queue} = window;
        aplus_queue.push({
          action: 'aplus.sendPV',
          arguments: [{
            is_auto: false
          }, {
            loginId, channel, userId, userNo, displayName, appId, version, deviceId
          }]
        });

        var ui = {
          ak: '650c128cb2f6fa00ba575571',
          sdt: channel,
          aid: loginId,
          uin: displayName,
          uig: userNo,
          uit: 'China',
          uic: appId,
          id: loginId,
          uil: 'Chinese',
          uia: 'no_avatar',
          it: 'loginId' //请与aplus-idtype值保持一致
        };
        if (window.aplus) {
          window.aplus.uploadUserProfile(JSON.stringify(ui),  (res) => {
            console.log('uploadUserProfile success: ', res);
          });
        }

        setTimeout(() => {
          const {aplus_queue} = window;
          if(aplus_queue) {
            aplus_queue.push({
              action: 'aplus.record',
              arguments: ['enter_video_index', 'CLK', {
                loginId, channel, userId, userNo, displayName, appId, version, deviceId
              }]
            });
          }
        }, 500)
      }, 500)
    }
    EventBus.$on('watchContinue', this.watchContinue)
  },
  onHide() {
    this.$refs.onlineCircle && this.$refs.onlineCircle.pauseAniEv()
    this.clearOnlineTxTimer();
    this.clearLingdangTimer();
    this.stopVideo()
  },
  async onShow() {
    if (isMpWeixin || isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
      let userInfo = app.globalData.userInfo;
      if (userInfo && userInfo.userId) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    }
    if (this.$refs.onlineCircle) {
      this.$refs.onlineCircle.playAniEv()
    }
    if (!isFirst) {
      await this.getAccout();
    }
    let onlineBeginNumber = app.globalData.onlineBeginNumber;
    if (onlineBeginNumber>0 && onlineBeginNumber < 180 && this.accountInfo?.activityDaily?.ftimes >= 4) {
      let userId = this.accountInfo.id || '';
      let today = dateFormat('YYYY-mm-dd', new Date()) +'_' + userId;
      this.startOnlineTxTimer(today);
    }

    let lingdangBeginNumber = app.globalData.lingdangBeginNumber;
    if (lingdangBeginNumber>0 && lingdangBeginNumber < 600) {
      let userId = this.accountInfo.id || '';
      let today = dateFormat('YYYY-mm-dd', new Date()) +'_' + userId;
      this.startJobLingdangTimer(today);
    }
  },
  beforeDestroy() {
    this.clearOnlineTxTimer();
    this.clearLingdangTimer()
    EventBus.$off('watchContinue', this.watchContinue)
  },
  options: { styleIsolation: 'shared' },
  methods: {
    returnBackEv() {
      this.$navigateBack()
    },
    watchContinue(item) {
      this.videoList.splice(this.currentIdx + 1)
      let obj = this.videoList[this.videoList.length - 1]

      obj.findex = item.findex
      obj.fcount = item.total;
      obj.name = item.name;
      obj.filmId = obj.id = item.id;
      obj.coverImg = item.coverImg;
      obj.url = item.filmUrl;
      obj.percent = 0;
      // this.videoList[this.videoList.length - 1] = obj

      if (isH5) {
        if (obj.dplayer) {
          obj.dplayer.switchVideo({
            url: obj.url,
            pic: obj.coverImg,
            thumbnails: obj.coverImg,
          });
          obj.dplayer.play()
        } else {
          this.initVideo(obj)
        }
      } else {
        this.playVideo(obj)
      }
      this.addNextEmpty()
    },
    async getMoneyDetail() {
      let res = await GetMoneyDetail()
      if (res && res.code == 200) {
        this.userPayaccount = res.data.userPayaccount || {};
      }
    },
    async signReceiveEv() {
      
      let id = this.accountInfo?.activityDaily?.id
      if (id) {
        
        if (!this.userPayaccount.accoutNo) {
          await this.getMoneyDetail()
        }

        if (this.userPayaccount.id == -1) {
          this.$showToast('尚未绑定提现账号，即将前往绑定')
          setTimeout(() => {
            this.$navigateTo(`/pages/welfare/bindAlipay?accoutName=&accoutNo=`)
          }, 2000)
          return;
        }

        this.isVisibleSignPop = false;
        RecvDaily({
          id
        }).then(res => {
          if (res.code == 200) {
            // this.$showToast('领取成功')
            
            this.isVisibleSignSuccess = true;

            if(isH5) {
              const {aplus_queue} = window;
              if(aplus_queue) {
                let { appId, channel, version, deviceId } = app.globalData
                let { userId, userNo, loginId, displayName } = app.globalData.userInfo || {};

                aplus_queue.push({
                  action: 'aplus.record',
                  arguments: ['daily_sign_cash', 'CLK', {
                    loginId, channel, userId, userNo, displayName, appId, version, deviceId
                  }]
                });
              }
            } else {
              let userInfo = app.globalData.userInfo;
              if (userInfo && userInfo.userId) {
                if (this.$uma && this.$uma.trackEvent) {
                  this.$uma.trackEvent('daily_sign_cash', userInfo);
                }
              }
            }
          }
        })
      }
    },
    clearOnlineTxTimer() {
      onlineTxTimer && clearInterval(onlineTxTimer)
    },
    startOnlineTxTimer(today) {
      let _self = this;
      let onlineBeginNumber = app.globalData.onlineBeginNumber;
      this.clearOnlineTxTimer();
      countFunc()

      onlineTxTimer = setInterval(() => {
        countFunc()
        app.globalData.onlineBeginNumber = onlineBeginNumber = onlineBeginNumber - 1;
      }, 1000)

      function countFunc() {
        onlineBeginNumber = onlineBeginNumber < 0 ? 0 : onlineBeginNumber;
        _self.countTxTxt = `${formatCountdown(Math.ceil(onlineBeginNumber))}`
        if (onlineBeginNumber <=0) {
          _self.clearOnlineTxTimer();
          setTimeout(() => {
            _self.countTxTxt = '';
            uni.setStorageSync('tixianThan3', today);
            app.globalData.onlineBeginNumber = onlineBeginNumber = 180;
          }, 500)
        }
      }
    },
    clearLingdangTimer() {
      lingdangTxtTimer && clearInterval(lingdangTxtTimer)
    },
    startJobLingdangTimer(today) {
      let _self = this;
      let lingdangBeginNumber = app.globalData.lingdangBeginNumber;

      this.clearLingdangTimer();
      countFunc()

      lingdangTxtTimer = setInterval(() => {
        countFunc()
        app.globalData.lingdangBeginNumber = lingdangBeginNumber = lingdangBeginNumber - 1;
      }, 1000)

      function countFunc() {
        lingdangBeginNumber = lingdangBeginNumber < 0 ? 0 : lingdangBeginNumber;
        _self.lingdangTxt = `${formatCountdown(Math.ceil(lingdangBeginNumber))}`
        if (lingdangBeginNumber <=0) {
          _self.clearLingdangTimer();
          setTimeout(() => {
            _self.lingdangTxt = '';
            // uni.setStorageSync('lingdangStage', today);
            app.globalData.lingdangBeginNumber = lingdangBeginNumber = 600;
          }, 500)
        }
      }
    },
    async getAccout() {
      let res = await GetAccout()
      if (res.code == 200 && res.data) {
        let data = res.data || {};
        let initAmount = data.initAmount
        if (initAmount) {
          data.initAmount = (initAmount/ 100).toFixed(2)
        } else {
          data.initAmount = '0.00';
        }
        this.accountInfo = data;
      }
    },
    getCurFilms(callback) {
      GetCurFilms().then(res => {
        if (res.code == 200 && res.data) {
          let obj = this.formatVideo(res.data, true);
          obj.randomId = this.generateRandom();
          console.log('当前 ', obj);
          this.videoList = [obj];
          callback && callback(res.data);
        }
      })
    },
    formatVideo(data, autoplay = false) {
      let { activityFilms, curUrl, filmId, findex } = data;
      let obj = {
        ...activityFilms,
        url: curUrl,
        videoId: `mv_${findex}`,
        filmId,
        findex,
        autoplay, 
        isPlaying: false, 
        speed: 1, 
        percent: 0, 
        dplayer: null
      }
      return obj
    },
    signPopHideEv() {
      this.isVisibleSignPop = false
      this.$refs.onlineCircle && this.$refs.onlineCircle.playAniEv()
    },
    receiveDailySuccessPopHideEv() {
      this.isVisibleSignSuccess = false
      this.$refs.onlineCircle && this.$refs.onlineCircle.playAniEv()
    },
    visibleSwiperItem(index) {
      let currentIdx = this.currentIdx;

      if (index == 0 && this.currentIdx == 0) {
        return true;
      } else {
        if (index == currentIdx-1 || index == currentIdx+1 || index == currentIdx) {
          return true;
        }
      }
      return false;
    },
    initVideo(obj) {
      let curVideo = obj || this.curVideoInfo;
      let container = document.getElementById(curVideo.randomId);
      console.log('container >> ', container);

      let dplayer = new DPlayer({
        autoplay: true,
        hotkey: false,
        container,
        video: {
          pic: curVideo.coverImg,
          thumbnails: curVideo.coverImg,
          url: curVideo.url,
        },
      });

      curVideo.dplayer = dplayer;
      dplayer.on('play', this.onPlay)
      dplayer.on('pause', this.onPause)
      dplayer.on('ended', this.onEnded)
      console.log('初始化 ： exec播放');
      dplayer.play()
    },
    generateRandom() {
      return `${new Date().getTime()}_${parseInt(Math.random() * 10000)}`;
    },
    async swiperChange(e) {
      let currentIdx = this.currentIdx
      let list = this.videoList;

      if (e.detail.current == currentIdx) {
        return;
      }
      
      this.stopVideo(list[currentIdx]);

      console.log('e.detail.current>> ', e.detail.current, currentIdx);
      if (e.detail.current > currentIdx) {
        let result = list[e.detail.current]
        let prev = list[currentIdx]
        if (!result.filmId) {
          let filmId = this.curVideoInfo.id || prev.id;
          let val = 1;
          if (prev && prev.findex == prev.fcount) {
            val = 2;
          }
          let obj = await this.fetchNextVideo(val, filmId)
          if (obj) {
            if (val == 2) {
              this.videoList.splice(this.currentIdx + 1)
            }
            let latest = this.videoList[this.videoList.length - 1]
            this.videoList[this.videoList.length - 1] = Object.assign(latest, obj)
            this.addNextEmpty()
          }
        }
        this.$nextTick(() => {
          if (isH5) {
            this.currentIdx = e.detail.current; 
            let obj = list[this.currentIdx]
            console.log('obj>> ', obj);
            if (!obj.dplayer) {
              this.initVideo(obj);
            } else {
              obj.dplayer.play();
            }
          } else {
            console.log('zzzxxxxxxxx index >', e.detail.current);
            this.currentIdx = e.detail.current; 
            list[this.currentIdx].autoplay = true
            this.playVideo(list[this.currentIdx])
          }
        })
      } else {
        this.currentIdx = e.detail.current;
        if (isH5) {
          let obj = list[this.currentIdx]
          if (!obj.dplayer) {
            this.initVideo(obj);
          } else {
            obj.dplayer.play();
          }
        } else {
          list[this.currentIdx].autoplay = true
          this.playVideo(list[this.currentIdx])
        }
      }
    },
    showTaskPop() {
      this.stopVideo();
      this.getAccout();
    },
    hideTaskPop() {
      this.playVideo();
    },
    playVideo(item) {
      console.log('触发播放', item);
      let video = item || this.curVideoInfo;
      console.log('playVideo>' ,video.randomId );
      if (isH5) {
        if (video.dplayer) {
          console.log('dplayer 播放');
          video.dplayer.play()
        } else {
          this.initVideo(video);
        }
      } else {
        let videoContext = uni.createVideoContext(video.randomId)
        video.autoplay = true;
        videoContext.play();
      }
    },
    stopVideo(item) {
      let video = item || this.curVideoInfo;
      console.log('stopVideo>' ,video.randomId );
      if (isH5) {
        if (video.dplayer) {
          video.dplayer.pause()
        }
      } else {
        // console.log(video);
        let videoContext = uni.createVideoContext(video.randomId)
        video.autoplay = false;
        videoContext.pause();
      }
    },
    clickVideo() {
      // let current = this.videoList[this.currentIdx]
      // console.log('clickVideo > ', current);
      // if (current) {
      //   if (current.isPlaying) {
      //     this.stopVideo(current)
      //   } else {
      //     this.playVideo(current)
      //   }
      // }
    },
    onPlay(e) {
      console.log('onPlay>' ,e.currentTarget.id );
      this.videoList[this.currentIdx].isPlaying = true;
    },
    onPause(e) {
      console.log('onPause>' ,e.currentTarget.id );
      this.videoList[this.currentIdx].isPlaying = false;
    },
    async onEnded(e) {
      let currentIdx = this.currentIdx;
      let nextIdx = currentIdx + 1;
      console.log('onEnded>', nextIdx );
  
      let list = this.videoList;
      let result = list[currentIdx]
      let nextObj = list[nextIdx];
      
      if (!nextObj.filmId) {
        let val = 1;
        if (result && result.findex == result.fcount) {
          val = 2;
        }
        let filmId = result.id; 
        let obj = await this.fetchNextVideo(val, filmId)
        if (obj) {
          let latest = this.videoList[this.videoList.length - 1]
          this.videoList[this.videoList.length - 1] = Object.assign(latest, obj)
          this.addNextEmpty()
        }
      }

      if (isH5) {
        this.currentIdx = nextIdx;
        this.$nextTick(() => {
          let obj = list[this.currentIdx]
          if (!obj.dplayer) {
            console.log('要初始化');
            this.initVideo(obj);
          } else {
            console.log('继续播放');
            obj.dplayer.play();
          }
        })
      } else {
        this.currentIdx = nextIdx; 
        this.$nextTick(() => {
          list[this.currentIdx].autoplay = true
          this.playVideo(list[this.currentIdx])
        })
      }
    },
    progressEv(e) {
      // console.log('progressEv>' ,e );
    },
    timeupdateEv(e) {
      // let obj = this.videoList.find(per => per.videoId == e.currentTarget.id)
      let obj;
      for (let len = this.videoList.length-1; len >= 0; len--) {
        let el = this.videoList[len];
        if (el.randomId == e.currentTarget.id) {
          obj = el;
          break;
        }
      }
      // console.log(' timeupdateEv == ', e.currentTarget, e.detail);
      if (obj) {
        let { currentTime, duration, videoDuration} = e.detail;
        videoDuration = videoDuration || duration;
        let percent = currentTime / videoDuration * 100;

        obj.currentTime = currentTime || 0;
        obj.videoDuration = videoDuration;
        obj.percent = percent > 100 ? 100 : percent;
        // console.log(' currentTime, videoDuration ',  currentTime, videoDuration, percent);
      }
    },
    addNextEmpty() {
      this.videoList.push({
        randomId: this.generateRandom(),
        percent: 0
      })
    },
    async fetchNextVideo(type = 1, filmId) {
      console.log('this.currentIdx> ', this.currentIdx);
      let next = this.videoList[this.currentIdx +1]
      console.log('newxt : ', next);
      filmId = filmId || this.curVideoInfo.id

      if (type == 1) {
        if (next && next.filmId) {
          return;
        }
      }
      console.log('this.loading : ', this.loading);
      if (this.loading) {
        return;
      }
      
      this.loading = true
      console.log('获取下一', type == 2 ? '部':'集');
      let params = {
        type,
        filmId
      }
      let res = await GetNextFilms(params)
      setTimeout(() => {
        this.loading = false;
      }, 300)
      if (res.code == 200) {
        let o = this.formatVideo(res.data)
        return o;
      }
      return null;
    },
    async firstReceiveEv() {
      let res = await ReceiveFirst({id: this.accountInfo.id})
      if (res.code == 200) {
        // 领取成功之后，弹出去提取
        this.isVisFirstPop = false;
        this.$refs.onlineCircle.showTaskPop();
        this.$showToast('领取成功，已发放到账号余额！')
        this.getAccout();
      }
    },
    showBeisu(e) {
      this.visibleVideoSpeed = true;
    },
    async switchOtherFilm() {
      // 修改下一部
      this.stopVideo()
      let obj = await this.fetchNextVideo(2)
      if (obj) {
        this.videoList.splice(this.currentIdx + 1)
        let latest = this.videoList[this.videoList.length - 1]
        this.videoList[this.videoList.length - 1] = Object.assign(latest, obj)
        this.addNextEmpty()
      }
      this.playVideo()
    },
    changePlaySpeed(item) {
      this.curVideoInfo.speed = item.value;
      if (isMpWeixin || isMpAlipay) {
        let videoContext = uni.createVideoContext(this.curVideoInfo.randomId)
        videoContext.playbackRate(item.value);
      } else if (this.curVideoInfo.dplayer) {
        this.curVideoInfo.dplayer.speed(item.value);
      }
      this.playVideo();
      this.visibleVideoSpeed = false;
    },
    toWatchHistory() {
      this.$navigateTo('/pages/welfare/watchHistory')
    },
    clickProcess(ev, item) {
      console.log('clickProcess ev, item >> ', ev, item);

      let winWidth = uni.getSystemInfoSync().windowWidth;
      let padding = uni.upx2px(64);
      let wth = winWidth - padding;
      let percent = ev.detail.pageX / wth;
     
      
      if (item && item.videoDuration ) {
        let seektime = parseInt(item.videoDuration * percent) 
        console.log('clickProcess ev>> ', item.videoDuration, percent, seektime);

        percent = percent > 1 ? 1 : percent
        item.percent = percent * 100;
        console.log('item.percent >> ', item.percent);

        let videoContext = uni.createVideoContext(item.randomId)
        videoContext.seek(seektime);
      }
    },
    toLogin() {
      this.$navigateTo('/pages/login/phone')
    },
    hideCmTip(e) {
      this.visibleCmTip = false;
    },
    showAwardFinishTip() {
      this.tipConfig = {
        title: '温馨提示',
        content: '当日奖励已发完，明天再来。',
        isConfirm: false,
        btnTxt: '好的，我知道了！',
      };
      this.visibleCmTip = true;
      setTimeout(() => {
        this.visibleCmTip = false;
      }, 3000)
    },
    hideJobTask() {
      this.visibleJobTask = false;
      this.playVideo();
      if (this.$refs.onlineCircle) {
        this.$refs.onlineCircle.playAniEv()
      }
    },
    clickLingdang() {
      this.visibleJobTask = true;
      this.stopVideo()
      // 暂停转圈
      if (this.$refs.onlineCircle) {
        this.$refs.onlineCircle.pauseAniEv()
      }
      // 触发事件
      if(isH5) {
        const {aplus_queue} = window;
        if(aplus_queue) {
          let { appId, channel, version, deviceId } = app.globalData
          let { userId, userNo, loginId, displayName } = app.globalData.userInfo || {};

          aplus_queue.push({
            action: 'aplus.record',
            arguments: ['video_bell_click', 'CLK', {
              loginId, channel, userId, userNo, displayName, appId, version, deviceId
            }]
          });
        }
      } else {
        let userInfo = app.globalData.userInfo;
        if (userInfo && userInfo.userId) {
          if (this.$uma && this.$uma.trackEvent) {
            this.$uma.trackEvent('video_bell_click', userInfo);
          }
        }
      }
    }
  },
};
</script>
<style lang="scss" scoped>
  $onlin_cic_lt_color:#FEC601;

  .index-page {
    width: 100%;
    background-color: #fff;
    overflow: hidden;
    height: 100vh;

    v-deep .u-swiper {
      margin-left: 0;
    }

    .film-info {
      position: fixed;
      left: 32rpx;
      bottom:226rpx;
      color:#fff;
      display: flex;
      .cover-img {
        width: 60rpx;
        min-width: 60rpx;
        height: 84rpx;
        margin-right: 12rpx;
        border-radius: 8rpx;
      }
    }
    .irght-info {
      position: fixed;
      right: 0;;
      top:190px;
      background: #f50;
      color: #fff;
      z-index: 1000;
    }

    .box-1 {
      position: relative;
      margin-bottom: 16rpx;
      background: linear-gradient(180deg,#f50,#F9EEE7);
      height: 100%;
      

      .inner-cont {
        position:relative;
        width: 100%;
        height: 100%;

        .swiper {
          width: 100%;
          height: 100%;
        }
      }

      .swiper-item {
        width: 100vw;
        height: 100%;

        .swiper-item-dom {
          position: relative;
          width: 100%;
          height: 100%;
        }
        

        .item-video {
          width: 100%;
          height: 100vh;
          object-position: top;
          object-fit:contain;
        }
      }
      
    }

    .tixiantip-block {
      position: fixed;
      top: 360rpx;
      right: 32rpx;
      width: 110rpx;
      padding: 12rpx 8rpx 8rpx;
      color: #fff;
      background: #0079FF;
      font-size: 26rpx;
      border-radius: 16rpx;
      text-align: center;

      .inn-box {
        margin-top: 8rpx;
        background: #fff;
        color: #0079FF;
        font-weight: bold;
        font-size: 28rpx;
        border-radius: 16rpx;
        text-align: center;
        padding: 10rpx 0;
        line-height: 32rpx;
      }
    }

    .job-clock-block {
      position: fixed;
      top: 360rpx;
      right: 32rpx;
      width: 106rpx;
      height: 106rpx;
      border-radius: 60px;
      background: #823014;
      border: 7rpx solid $onlin_cic_lt_color;

      &.geng-block {
        top: 520rpx;
      }


      .lingdang {
        position: absolute;
        left: 0;
        right: 0;
        width: 58rpx;
        height: 58rpx;
        margin: 14rpx auto 0;
        animation: lingdangAni 3s ease infinite;

        // animation-name: lingdangAni;
        // animation-duration: 3s;
        // animation-iteration-count: infinite;

        // &.init-show {
        //   animation: zoomAni 1s forwards;
        //   animation-fill-mode: forwards;
        // }
      }

      .down-num {
        position: absolute;
        bottom: -10px;
        color: #fff;
        font-size: 12px;
        text-align: center;
        left: -7rpx;
        width: 106rpx;
        margin-left: 0;
        height: 20px;
        line-height: 20px;
        border-radius: 11px;
        background: linear-gradient( 90deg, #FF282D 0%, #FF752B 100%);
        .e-txt {
          display: inline-block;
          transform: scale(0.8);
          -webkit-transform: scale(0.8);
        }
      }
    }

    .beisu {
      position: fixed;
      bottom: 56rpx;
      left: 32rpx;
      color: #fff;
      font-size: 24rpx;
      z-index: 10;
    }  
    .right-bottom {
      position: fixed;
      bottom: 56rpx;
      right: 32rpx;
      display: flex;

      .watch-log, .change-mv, .zan-kls {
        color: #fff;
        font-size: 24rpx;
        img, image {
          width: 56rpx;
          height: 56rpx;
          margin: 0 auto 10rpx;
          display: block;
        }
      }  
    }
    

    .speed-hd {
      padding: 60rpx 0px 48rpx;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
    }
    .speed-content {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 24px 200px;

      .speed-option {
        width: calc((100vw - 72px) / 3);
        background: #EFEFEF;
        border-radius: 2px;
        text-align: center;
        height: 40px;
        line-height: 40px;
        margin-bottom: 12px;
        border-radius: 16rpx;

        &.active {
          background: #FFE9EA;
          color:#FF282D;
        }
      }
    }

    .process-bar {
      position: absolute;
      height: 10px;
      display: flex;
      align-items: center;
      left: 32rpx;
      right: 32rpx;
      bottom: 180rpx;
      z-index: 10;
      overflow: hidden;

      .bar-bg {
        position: relative;
        background: #787878;
        border-radius: 2px;
        height: 2px;
        border-radius: 2px;
        width: 100%;
      }
      .process-ing {
        width:0;
        height: 2px;
        background: #fff;
      }
    }
  }

  
.pop-rec-btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 156rpx;
  margin: 0 auto;

  width: 400rpx;
  height: 84rpx;
  line-height: 84rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 32rpx;
  text-align: center;
  background: linear-gradient( 79deg, #FF282D 0%, #FF752B 100%);
}
.close-ico {
  width: 72rpx;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  z-index: 10;
}
.zuigao {
  position:absolute;
  width: 58rpx;
  height:32rpx;
  margin-top: 44rpx;
  margin-left: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  background:#FFD7CF;
  border-radius:10rpx;
}
.tx-info {
  text-align: center;
  border-radius: 32rpx;
  padding: 32rpx;
  margin-top: 50rpx;
  background-color: #fff;
  background-repeat: no-repeat;
  background-position: 93% 18%;
}


@keyframes zoomAni {
  0% {
    -webkit-transform: scale(0);
  }
  70% {
    -webkit-transform: scale(1.2);
  }
  100% {
    -webkit-transform: scale(1);
  }
}

@keyframes lingdangAni {
  0%, 75% {
    -webkit-transform: rotate(0deg);
  }
  80% {
    -webkit-transform: rotate(45deg);
    -webkit-transform-origin: 50% 5px;
  }
  85% {
    -webkit-transform: rotate(-45deg);
    -webkit-transform-origin: 50% 5px;
  }
  92% {
    -webkit-transform: rotate(35deg);
    -webkit-transform-origin: 50% 5px;
  }
  96% {
    -webkit-transform: rotate(-25deg);
    -webkit-transform-origin: 50% 5px;
  }
  100% {
    -webkit-transform: rotate(0deg);
    -webkit-transform-origin: 50% 5px;
  }
}
</style>
